/**
 * 网络请求配置
 */
// @ts-nocheck
import axios from "axios";
import {
  getAccessToken, removeAll,
} from '@/utils/authority';
import { Toast } from "antd-mobile";
import { IResData } from "..";
axios.defaults.timeout = 100000;
axios.defaults.headers.post['Content-Type'] = "application/json";
axios.defaults.headers.head.Authorization = 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0';

const appUrl = ''//'http://10.0.204.9:80'
const apiUrl = ''//'http://10.0.204.9:18003'
// axios.defaults.baseURL = "http://10.0.204.9:8000";

/**
 * http request 拦截器
 */
axios.interceptors.request.use(
  (config) => {
    config.headers = {
      ...config.headers,
      'Authorization': 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0',
      'Tenant-Id': '000000',
      'Keeper-Auth': `bearer ${getAccessToken()}`
    
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * http response 拦截器
 */
axios.interceptors.response.use(
  (response) => {
    if (response?.data?.errCode === 2) {
      console.log("过期");
    }
    return response;
  },
  (error) => {
    console.log(error,'11111')
    // 如果错误信息里是401 则说明是token过期
    console.log(error.toString())
    if(error.toString().includes("401")){
      const errRes:IResponseDate<any> = {
        code:401,
        success:false,
        data:[],
        msg:"登录过期，请重新登录"
      }
      handleTokenTimeout(errRes)
    }

    console.log("请求出错：", error);
    return error;
  }
);

/**
 * 封装get方法
 * @param url  请求url
 * @param params  请求参数
 * @returns {Promise}
 */
export function get<T>(url:string, params = {}):Promise<IResponseDate<T>> {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
    }).then((response) => {
      landing(url, params, response?.data);
      resolve(response?.data);
    })
      .catch((error) => {
        reject(error);
      });
  });
}

export const formdataify = (params) => {
  // console.log(params)
  const formData = new FormData();
  Object.keys(params).forEach(key => {
    if (typeof params[key] == "string") {
      // console.log(params[key])
      formData.append(key, params[key]);
    } else {
      formData.append(key, JSON.stringify(params[key]));
    }
  });
  return formData;
};
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */



export function post<T>(url:string, data):Promise<IResponseDate<T>> {
  // console.log(data);
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      (response) => {
        //关闭进度条
        resolve(response?.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url: any, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data).then(
      (response) => {
        resolve(response?.data);
      },
      (err) => {
        msag(err);
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response?.data);
      },
      (err) => {
        msag(err);
        reject(err);
      }
    );
  });
}




interface IResponseDate<T>{
  code:number;
  data:T;
  msg:string;
  success:boolean;
}

export const handleTokenTimeout = (response:IResponseDate<string>) =>{

  if(response.code === 401){
    // 401表示token过期，删掉所有的token和用户信息
    Toast.show({
      icon: 'fail',
      content: response.msg
    })
    removeAll();
    setTimeout(() => {
      window.location.href = window.location.origin + "/";
    }, 1000)
  }
}

//统一接口处理，返回数据
export default function<T> (fecth:"get"|"post", url:string, param):Promise<IResData<T>> {
  if(appUrl && url.search('/app/') >= 0){
    url = url.replace('/app',appUrl)
  }else if(apiUrl && url.search('/api/') >= 0){
    url = url.replace('/api',apiUrl)
  }
  return new Promise((resolve, reject) => {
    switch (fecth) {
      case "get":
        get<T>(url, param)
          .then(function (response) {
            resolve(response);
          })
          .catch(function (error) {
            console.log("get request GET failed.", error);
            reject(error);
          });
        break;
      case "post":
        post(url, param)
          .then(function (response) {
            resolve(response);
          })
          .catch(function (error) {
            console.log("get request POST failed.", error);
            reject(error);
          });
        break;
      default:
        break;
    }
  });
}

//失败提示
function msag(err) {
  if (err && err?.response) {
    switch (err?.response?.status) {
      case 400:
        alert(err?.response?.data?.error?.details);
        break;
      case 401:
        alert("未授权，请登录");
        break;

      case 403:
        alert("拒绝访问");
        break;

      case 404:
        alert("请求地址出错");
        break;

      case 408:
        alert("请求超时");
        break;

      case 500:
        alert("服务器内部错误");
        break;

      case 501:
        alert("服务未实现");
        break;

      case 502:
        alert("网关错误");
        break;

      case 503:
        alert("服务不可用");
        break;

      case 504:
        alert("网关超时");
        break;

      case 505:
        alert("HTTP版本不受支持");
        break;
      default:
    }
  }
}

/**
 * 查看返回的数据
 * @param url
 * @param params
 * @param data
 */
function landing(url, params, data) {
  if (data?.code === -1) {
  }
}

